package cn.xiangxu.demo.sell_demo.util.converter;

import cn.xiangxu.demo.sell_demo.entity.entityDTO.OrderDTO;
import cn.xiangxu.demo.sell_demo.entity.entityForm.OrderForm;
import cn.xiangxu.demo.sell_demo.entity.entityPO.OrderDetailPO;
import cn.xiangxu.demo.sell_demo.enums.ResultEnum;
import cn.xiangxu.demo.sell_demo.exceptions.SellException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderForm2OrderDTO {

    public static OrderDTO convert(OrderForm orderForm) {
        Gson gson = new Gson();

        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        List<OrderDetailPO> orderDetails = new ArrayList<>();

        try {
            orderDetails = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetailPO>>(){}.getType());
        } catch (Exception e) {
            log.error("【JSON字符串转换成对象出错】-string={}", orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }

        orderDTO.setOrderDetailPOList(orderDetails);

        return orderDTO;
    }
}
